﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows;
using System.Data;
using DSPL.Services;
using DSPL.Services.Services;
using DSPL.Contracts;
using DSPL.Contracts.Common;
using System.ComponentModel;
using System.Windows.Controls;
using System.Windows.Media;
using DSPL.Common.CommonControls.Controls;
using DSPL.Contracts.Interfaces;
using DSPL.Contracts.ViewModel;
using DSPL.Contracts.Command;
using DSPL.Finac.Common;
using DSPL.Common;


namespace DSPL.Finac.ViewModel
{
    public class SupplierMasterViewModel : BaseViewModel
    {
        #region Private Variables

        private DataTable _dtCreditorTax;
        private DataTable _dtStatus;
        private Dictionary<string, string> _bindSupplierGroup = new Dictionary<string, string>();
        private bool isSupCodeFocused;
        private bool isSupNameFocused;
        private bool isStatusFocused;
        private bool isSupAdvCodeFocused;
        private bool isSupCntCodeFocused;
        private bool isGainLossFocused;
        private bool isSupplierGroupFocused;
        private bool isCreditPeriodChecked;
        private bool isTaxReadOnly;
        private ICommand taxRegClick;
        private ICommand taxCodeLostFocus;
        private Visibility _isGainAccVisible;

        #endregion

        #region Properties

        public bool IsSupCodeFocused
        {
            get { return isSupCodeFocused; }
            set
            {
                isSupCodeFocused = value;
                this.OnPropertyChanged("IsSupCodeFocused");

            }
        }

        public bool IsSupNameFocused
        {
            get { return isSupNameFocused; }
            set
            {
                isSupNameFocused = value;
                this.OnPropertyChanged("IsSupNameFocused");

            }
        }

        public bool IsStatusFocused
        {
            get { return isStatusFocused; }
            set
            {
                isStatusFocused = value;
                this.OnPropertyChanged("IsStatusFocused");

            }
        }

        public bool IsSupAdvCodeFocused
        {
            get { return isSupAdvCodeFocused; }
            set
            {
                isSupAdvCodeFocused = value;
                this.OnPropertyChanged("IsSupAdvCodeFocused");

            }
        }

        public bool IsSupCntCodeFocused
        {
            get { return isSupCntCodeFocused; }
            set
            {
                isSupCntCodeFocused = value;
                this.OnPropertyChanged("IsSupCntCodeFocused");
            }
        }


        public bool IsGainLossFocused
        {
            get { return isGainLossFocused; }
            set
            {
                isGainLossFocused = value;
                this.OnPropertyChanged("IsGainLossFocused");

            }
        }

        public bool IsSupplierGroupFocused
        {
            get { return isSupplierGroupFocused; }
            set
            {
                isSupplierGroupFocused = value;
                this.OnPropertyChanged("IsSupplierGroupFocused");

            }
        }


        public bool IsCreditPeriodChecked
        {
            get { return isCreditPeriodChecked; }
            set
            {
                isCreditPeriodChecked = value;
                this.OnPropertyChanged("IsCreditPeriodChecked");

            }
        }

        public bool IsCreditLimitChecked
        {
            get { return isCreditPeriodChecked; }
            set
            {
                isCreditPeriodChecked = value;
                this.OnPropertyChanged("IsCreditPeriodChecked");

            }
        }


        public bool IsTaxReadOnly
        {
            get { return isTaxReadOnly; }
            set { isTaxReadOnly = value; }
        }

        public DataTable DtCreditorTax
        {
            get { return _dtCreditorTax; }
            set
            {
                _dtCreditorTax = value;
                this.OnPropertyChanged("DtCreditorTax");
            }
        }


        public DataTable DtStatus
        {
            get { return _dtStatus; }
            set
            {
                _dtStatus = value;
                this.OnPropertyChanged("DtStatus");
            }
        }

        public Dictionary<string, string> BindSupplierGroup
        {
            get { return _bindSupplierGroup; }
            set
            {
                _bindSupplierGroup = value;
                this.OnPropertyChanged("BindSupplierGroup");

            }
        }

        public Visibility IsGainAccVisible
        {
            get { return _isGainAccVisible; }
            set
            {
                _isGainAccVisible = value;
                this.OnPropertyChanged("IsGainAccVisible");
            }
        }
        #endregion

        #region Define relay commands

        public ICommand TaxRegClick
        {
            get
            {
                if (this.taxRegClick == null)
                    this.taxRegClick = new RelayCommand(TaxRegClicked);

                return this.taxRegClick;
            }
        }

        public ICommand TaxCodeLostFocus
        {
            get
            {
                if (this.taxCodeLostFocus == null)
                    this.taxCodeLostFocus = new RelayCommand(TaxCodeLostFocusExecuted);

                return this.taxCodeLostFocus;
            }
        }


        #endregion
        #region Constructor
        public SupplierMasterViewModel()
            : base()
        {
            MessageTitle = "Supplier Master";
        }
        #endregion

        protected override void RefreshExternalDataObjectsExecueted(object obj)
        {

            base.RefreshExternalDataObjectsExecueted(obj);
         
            SetTaxRegistrationData();

            if (FormMode == Modes.New)
            {
                CurrentRow["Status"] = 1;
                OnPropertyChanged("CurrentRow");

            }

        }

        private void TaxRegClicked(object obj)
        {
            SetTaxRegistrationData();
        }


        /// <summary>
        /// To validate mandatory fields
        /// </summary>
        /// <returns></returns>
        /// <summary>
        /// Validate mandatory data before save
        /// </summary>
        /// <param name="obj"></param>
        protected override void PreDataValidateExecuted(object obj)
        {
            IsSupCodeFocused = false;
            IsSupNameFocused = false;
            IsStatusFocused = false;
            IsSupCntCodeFocused = false;
            IsSupAdvCodeFocused = false;
            IsGainLossFocused = false;
            IsSupplierGroupFocused = false;
            var messageService = new MessageService();
            if (CurrentRow["SupCode"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.SupplierNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["SupName"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.SupplierNameNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupNameFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["Status"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.SupplierTypeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsStatusFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["SupCntAcc"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.SupplierAcCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupCntCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["SupAdvAcc"].ToString().Trim() == string.Empty)
            {
                messageService.ShowMessage(MessageText.SupplierAdvAcCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupAdvCodeFocused = true;
                this.IsValid = false;
                return;
            }

            if ((IsGainAccVisible == Visibility.Visible) && (CurrentRow["SupGainLos"].ToString().Trim() == string.Empty))
            {
                messageService.ShowMessage(MessageText.SupplierGainLossAcCodeNotEmpty, MessageTitle, MessageType.InfoOK);
                IsGainLossFocused = true;
                this.IsValid = false;
                return;
            }

            if (CurrentRow["CreGrpPk"] == DBNull.Value || Convert.ToInt32(CurrentRow["CreGrpPk"]) == 0)
            {
                messageService.ShowMessage(MessageText.SupplierGroupNotEmpty, MessageTitle, MessageType.InfoOK);
                IsSupplierGroupFocused = true;
                this.IsValid = false;
                return;
            }

            DtCreditorTax.AcceptChanges();
            DataTable dtCreditorTax = DtCreditorTax.DefaultView.ToTable();

            foreach (DataRow drCreditorTax in dtCreditorTax.Rows)
            {
                if ((drCreditorTax["TaxCode"].ToString().Trim() == string.Empty) && (drCreditorTax["TaxRegNo"].ToString().Trim() == string.Empty))
                    continue;
                if ((drCreditorTax["TaxCode"].ToString().Trim() == string.Empty) || (drCreditorTax["TaxRegNo"].ToString().Trim() == string.Empty))
                {
                    messageService.ShowMessage(MessageText.TaxCodeRegNoNotEmpty, MessageTitle, MessageType.InfoOK);
                    this.IsValid = false;
                    return;
                }
            }

            DataRow[] validRecords = DtCreditorTax.Select("TaxCode <>''");
            if ((CurrentRow["TaxReg"] !=DBNull.Value && Convert.ToInt32(CurrentRow["TaxReg"]) == 1) && (validRecords.Length == 0))
            {
                messageService.ShowMessage(MessageText.InvalidTaxData, MessageTitle, MessageType.InfoOK);
                this.IsValid = false;
                if (DtCreditorTax.Rows.Count == 0)
                {
                    DataRow drNewTax = DtCreditorTax.NewRow();
                    drNewTax["TaxCode"] = "";
                    drNewTax["TaxRegNo"] = "";
                    DtCreditorTax.Rows.Add(drNewTax);
                }
                return;
            }

            this.IsValid = true;
            return;
        }

        /// <summary>
        /// To delete related records from child tables before deletes the master data.
        /// </summary>
        /// <returns></returns>
        protected override void PreDataDeleteExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.DeleteSupplierSpecificData(Convert.ToInt32(CurrentRow["SupplierPk"]), ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }

        }

        /// <summary>
        /// To build up the insert statements to update related child tables.
        /// </summary>
        /// <param name="writeData"></param>
        /// <returns></returns>
        /// 
        protected override void PostDataUpdateExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.UpdateSupplierTaxData(CurrentRow, DtCreditorTax, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }

        }


        /// <summary>
        /// To build up the insert statements to update related child tables.
        /// </summary>
        /// <param name="writeData"></param>
        /// <returns></returns>
        /// 
        protected override void PostDataInsertExecuted(object obj)
        {
            var commonService = new MasterWriteService();
            var sqlTran = this.SqlTran;
            if (!commonService.UpdateSupplierTaxData(CurrentRow, DtCreditorTax, ref sqlTran))
            {
                this.IsValid = false;
            }
            else
            {
                this.IsValid = true;
                this.SqlTran = sqlTran;
            }

        }

        private void TaxCodeLostFocusExecuted(object obj)
        {
            string taxCode = ((TxtMaster)obj).Code;
            var messageService = new MessageService();
            if (taxCode != string.Empty)
            {
                DataRow[] duplicateRows = _dtCreditorTax.Select("TaxCode='" + taxCode + "'");
                if (duplicateRows.Length >= 1)
                {
                    messageService.ShowMessage(MessageText.TaxCodeDuplicate, MessageTitle, MessageType.InfoOK);

                    DataRow drLastRow = duplicateRows[duplicateRows.Length - 1];
                    ((TxtMaster)obj).Code = "";
                }
            }

        }


        private void SetTaxRegistrationData()
        {
            int SupCode = 0;
            bool isEnabled = true;
            if (CurrentRow["TaxReg"]!=DBNull.Value && Convert.ToInt32(CurrentRow["TaxReg"]) == 1)
            {
                SupCode = (CurrentRow["SupplierPk"] == DBNull.Value ? 0 : (int)CurrentRow["SupplierPk"]);
                isEnabled = true;
            }
            else
            {
                SupCode = 0;
                isEnabled = false;
            }

            var getMasterData = new MasterReadService();
            DtCreditorTax = getMasterData.GetSupplierTaxData(SupCode);

            IsTaxReadOnly = !isEnabled;

        }


        protected override void SetDataSourcesAndProperties()
        {
            _dtStatus = new DataTable();
            _dtStatus.Columns.Add("Status");
            _dtStatus.Columns.Add("Title");
            _dtStatus.Rows.Add(1, "Active");
            _dtStatus.Rows.Add(0, "Inactive");
            _dtStatus.Rows.Add(2, "Blacklist");

            BindSupplierGroup.Add("CrGrName", "txtSupplierGrpTitle");

        }

        private void TextLostFocusExecuted(object obj)
        {

        }

        protected override void EnableDisableSpecificControls()
        {
            base.EnableDisableSpecificControls();

            if (GlobalVariables.SystemCurrency == "LOCAL")
            {
                IsGainAccVisible = Visibility.Hidden;
            }
            else
            {
                IsGainAccVisible = Visibility.Visible;
            }

        }

        protected override void PreDataInsertExecuted(object obj)
        {
            if (CurrentRow["TaxReg"] ==DBNull.Value)
            {
                CurrentRow["TaxReg"] = 0;
            }

            if (CurrentRow["ChkCrdPrd"]== DBNull.Value)
            {
                CurrentRow["ChkCrdPrd"] = 0;
            }

            if (CurrentRow["ChkCrdLmt"] == DBNull.Value)
            {
                CurrentRow["ChkCrdLmt"] = 0;
            }
        }

       

    }
}


